//
//  SearchViewController.m
//  PetAPP
//
//  Created by apple on 16/2/24.
//  Copyright © 2016年 Yuming. All rights reserved.
//

#import "SearchViewController.h"
#import "KeyInputTextFiled.h"
#import "NetworkingHandle.h"
#import "ModelOfSearchTag.h"
#import "ModelOfSearchThread.h"
#import "ModelOfSearchUser.h"
#import "CellOfSearchForTag.h"
#import "CellOfSearchForUser.h"
#import "CellOfSearchForThread.h"
#import "DataBaseHandle.h"
#import "SearchOfFlowLayout.h"
#import "CellOfSearchForCollection.h"

@interface SearchViewController () <UICollectionViewDataSource, UICollectionViewDelegate, UITextFieldDelegate, KeyInputTextFiledDelegate, UITableViewDataSource, UITableViewDelegate, SearchOfFlowLayoutDelegate, UICollectionViewDelegateFlowLayout>

@property (nonatomic, retain) KeyInputTextFiled *textFieldOfSearch;

@property (nonatomic, retain) UILabel *labelOfNumb;

@property (nonatomic, retain) UIView *viewOfHistory;

@property (nonatomic, retain) UIView *viewOfHotSearch;

@property (nonatomic, retain) UICollectionView *collectionOfHistory;

@property (nonatomic, retain) UICollectionView *collectionOfHot;

@property (nonatomic, retain) NSTimer *timerOfSearch;

@property (nonatomic, retain) UITableView *tableView;

@property (nonatomic, retain) NSMutableArray *tagArr;

@property (nonatomic, retain) NSMutableArray *threadArr;

@property (nonatomic, retain) NSMutableArray *userArr;

@property (nonatomic, retain) NSArray *hotTagArr;

@property (nonatomic, retain) NSMutableArray *historyArr;

@end

@implementation SearchViewController

- (void)dealloc {
    [_historyArr release];
    [_hotTagArr release];
    [_tagArr release];
    [_threadArr release];
    [_userArr release];
    [_tableView release];
    [_timerOfSearch release];
    [_collectionOfHistory release];
    [_collectionOfHot release];
    [_viewOfHotSearch release];
    [_viewOfHistory release];
    [_labelOfNumb release];
    [_textFieldOfSearch release];
    [super dealloc];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithRed:0.9686 green:0.9686 blue:0.9686 alpha:1.0];
    [self createHeaderView];
    [self createSubViews];
    [self createTableView];
    [self handleStaticData];
    
}

#pragma mark - 搜索之前静态数据
- (void)handleStaticData {
    
    [NetworkingHandle handleWorkData:@"http://bbs.chinapet.com/plugin.php?id=leepet_thread:api&action=searchHostContent" AndBody:@"service=searchHostContent&sign=bc32cd7110ec726db55f5f0c0838e7d8&version=d1bd83a33f1a841ab7fda32449746cc4" value:@{@"Content-Type" : @"application/x-www-form-urlencoded"} handleBlock:^(id result) {
        self.hotTagArr = [result objectForKey:@"data"];
        [self.collectionOfHot reloadData];
    }];

}


#pragma mark - 搜索以后数据处理
- (void)handleData {
    
    NSString *strOfBody = [NSString stringWithFormat:@"keyword=%@&uid=%@&version=d1bd83a33f1a841ab7fda32449746cc4", self.textFieldOfSearch.text, [[NSUserDefaults standardUserDefaults] stringForKey:@"uid"]];
    
    [NetworkingHandle handleWorkData:@"http://api.leepet.com/?m=DZ&a=foundSearchByKeyword" AndBody:strOfBody value:@{@"Content-Type" : @"application/x-www-form-urlencoded"} handleBlock:^(id result) {
        NSDictionary *tempDic = [[result objectForKey:@"data"] objectForKey:@"info"];
        
        
        self.tagArr = [NSMutableArray array];
        self.threadArr = [NSMutableArray array];
        self.userArr = [NSMutableArray array];
        

        for (NSString *key in tempDic) {
            if ([key isEqualToString:@"threadArr"]) {
                NSArray *threadArr = [tempDic objectForKey:key];
                for (NSDictionary *dic in threadArr) {
                    ModelOfSearchThread *model = [[ModelOfSearchThread alloc] init];
                    [model setValuesForKeysWithDictionary:dic];
                    [self.threadArr addObject:model];
                    [model release];
                }
                
            }else if ([key isEqualToString:@"tagArr"]) {
                NSArray *tagArr = [tempDic objectForKey:key];
                for (NSDictionary *dic in tagArr) {
                    ModelOfSearchTag *model = [[ModelOfSearchTag alloc] init];
                    [model setValuesForKeysWithDictionary:dic];
                    [self.tagArr addObject:model];
                    [model release];
                    
                }
            }else {
                NSArray *userArr = [tempDic objectForKey:key];
                for (NSDictionary *dic in userArr) {
                    ModelOfSearchUser *model = [[ModelOfSearchUser alloc] init];
                    [model setValuesForKeysWithDictionary:dic];
                    [self.userArr addObject:model];
                    [model release];
                    
                }
            }
        }
        
        [self.tableView reloadData];
        
        self.viewOfHistory.hidden = YES;
        self.viewOfHotSearch.hidden = YES;
        self.tableView.hidden = NO;
        
    }];
    


}

#pragma mark - 设置tableViewCell样式 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    switch (indexPath.section) {
        case 0:{
            CellOfSearchForTag *cell = [tableView dequeueReusableCellWithIdentifier:@"poolOfCellForTag"];
            cell.backgroundColor = [UIColor whiteColor];
            ModelOfSearchTag *model = [self.tagArr objectAtIndex:indexPath.row];
            
            [cell handleDataWithModel:model];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            /** 设置通过搜索设置可变字符串 */
            NSMutableAttributedString *attribute = [[NSMutableAttributedString alloc] initWithString:model.tagname];
            
            [attribute addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:[model.tagname rangeOfString:self.textFieldOfSearch.text]];
            
            [cell.labelOfName setAttributedText:attribute];
            [attribute release];
            
            return cell;
            break;
        }
        case 1:{
            CellOfSearchForThread *cell = [tableView dequeueReusableCellWithIdentifier:@"poolOfCellForThread"];
            ModelOfSearchThread *model = [self.threadArr objectAtIndex:indexPath.row];
            
            [cell handleDataWithModel:model];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            /** 设置通过搜索设置可变字符串 */
            NSMutableAttributedString *attribute = [[NSMutableAttributedString alloc] initWithString:model.message];
            
            [attribute addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:[model.message rangeOfString:self.textFieldOfSearch.text]];
            
            [cell.labelOfTitle setAttributedText:attribute];
            [attribute release];
            
            return cell;
            break;
        }
        default:{
            CellOfSearchForUser *cell = [tableView dequeueReusableCellWithIdentifier:@"poolOfCellForUser"];
            ModelOfSearchUser *model = [self.userArr objectAtIndex:indexPath.row];
            [cell handleDataWithModel:model];            
            
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            /** 设置通过搜索设置可变字符串 */
            NSMutableAttributedString *attribute = [[NSMutableAttributedString alloc] initWithString:model.username];
            
            [attribute addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:[model.username rangeOfString:self.textFieldOfSearch.text]];
            
            [cell.labelOfName setAttributedText:attribute];
            [attribute release];

            
            return cell;
            break;
        }
    }

}

#pragma mark - 设置头部大小
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {

    return 30;

}

#pragma mark - 设置头部分区显示内容
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *view = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)] autorelease];
    view.backgroundColor = [UIColor whiteColor];
    
    UILabel *labelOfText = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 100, 20)];
    [view addSubview:labelOfText];
    [labelOfText release];
    labelOfText.textColor = [UIColor colorWithRed:0.5932 green:0.5932 blue:0.5932 alpha:1.0];
    switch (section) {
        case 0:
            labelOfText.text = @"标签";
            break;
        case 1:
            labelOfText.text = @"帖子";
            break;
        default:
            labelOfText.text = @"用户";
            break;
    }
    
    
    return view;
}


#pragma mark - 设置脚步分区间隔大小
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {

    return 10;
}

#pragma mark - 设置脚步分区间隔
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    UIView *view = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 10)] autorelease];
    view.backgroundColor = [UIColor colorWithRed:0.9248 green:0.9248 blue:0.9248 alpha:1.0];


    return view;
}

#pragma mark - 设置tbleView分区行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 0:
            return self.tagArr.count;
            break;
        case 1:
            return self.threadArr.count;
            break;
            
        default:
            return self.userArr.count;
            break;
    }
}

#pragma mark - 设置tableVIew分区

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

#pragma mark - 创建tableView 

- (void)createTableView {

    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 60, self.view.frame.size.width, self.view.frame.size.height - 60) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    [_tableView release];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    [self.tableView registerClass:[CellOfSearchForTag class] forCellReuseIdentifier:@"poolOfCellForTag"];
    
    [self.tableView registerClass:[CellOfSearchForThread class] forCellReuseIdentifier:@"poolOfCellForThread"];
    
    [self.tableView registerClass:[CellOfSearchForUser class] forCellReuseIdentifier:@"poolOfCellForUser"];
    
    self.tableView.hidden = YES;
    
    self.tableView.rowHeight = 70;
    
}

#pragma mark - tableVIew点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSArray *result = [[DataBaseHandle shareDataBaseHandle] selectAllWithList:@"history" AndListNumber:2];
    self.historyArr = [NSMutableArray array];
    for (NSArray *arr in result) {
        [self.historyArr addObject:arr[1]];
    }
    
    if (![self.historyArr containsObject:self.textFieldOfSearch.text]) {
        NSString *SQL = [NSString stringWithFormat:@"insert into history(content) values('%@')", self.textFieldOfSearch.text];
        [[DataBaseHandle shareDataBaseHandle] updateSQL:SQL];
        
        [self.historyArr insertObject:self.textFieldOfSearch.text atIndex:0];
        
        [self.collectionOfHistory reloadData];
        [self.collectionOfHot reloadData];
        
    }
}

#pragma mark - collectionView点击iten的代理方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == self.collectionOfHistory) {
        self.textFieldOfSearch.text = self.historyArr[indexPath.item];
        [self textFieldDidChange:self.textFieldOfSearch];
    }else {
        self.textFieldOfSearch.text = self.hotTagArr[indexPath.item];
        [self textFieldDidChange:self.textFieldOfSearch];
    }
    

}



#pragma mark - 拖动手势
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {

    [self.view endEditing:YES];

}


#pragma mark - 设置collectionViewcell样式
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    CellOfSearchForCollection *cell = nil;
    if (collectionView == self.collectionOfHot) {
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"poolOfCellForHot" forIndexPath:indexPath];
    }else {
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"poolOfCellForHistory" forIndexPath:indexPath];
    
    }
    
    cell.backgroundColor = [UIColor whiteColor];
    cell.layer.cornerRadius = 7.0f;
    cell.layer.borderWidth = 0.5f;
    cell.layer.borderColor = [UIColor grayColor].CGColor;
    cell.layer.masksToBounds = YES;
    NSString *content = nil;
    if (collectionView == self.collectionOfHot) {
        content = self.hotTagArr[indexPath.item];
        
    }else {
        content = self.historyArr[indexPath.item];
    }
    
    CGRect itemFrame = [content boundingRectWithSize:CGSizeMake(0, 20) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:17]} context:nil];
    
    [cell HandleDataWithText:content AndWidth:itemFrame.size.width];
    
    
    return cell;
}


#pragma mark - 设置Collectioncell行数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (collectionView == self.collectionOfHot) {
        return self.hotTagArr.count;
    }else{
        return self.historyArr.count;
    }
}

#pragma mark - 创建历史搜索图层
- (void)createSubViews {
    

    self.viewOfHistory = [[UIView alloc] initWithFrame:CGRectMake(0, 60, self.view.frame.size.width, 60)];
    [self.view addSubview:self.viewOfHistory];
    [_viewOfHistory release];
    self.viewOfHistory.backgroundColor = [UIColor colorWithRed:0.9686 green:0.9686 blue:0.9686 alpha:1.0];
    
    UIImageView *imageViewOfHistory = [[UIImageView alloc] initWithFrame:CGRectMake(0, 5, self.view.frame.size.width, 35)];
    imageViewOfHistory.image = [UIImage imageNamed:@"historySearch"];
    [self.viewOfHistory addSubview:imageViewOfHistory];
    [imageViewOfHistory release];
    imageViewOfHistory.userInteractionEnabled = YES;
    /** 创建清除button */
    UIButton *buttonOfClear = [UIButton buttonWithType:UIButtonTypeCustom];
    buttonOfClear.backgroundColor = [UIColor clearColor];
    [imageViewOfHistory addSubview:buttonOfClear];
    [buttonOfClear addTarget:self action:@selector(handleClearAction) forControlEvents:UIControlEventTouchUpInside];
    buttonOfClear.frame = CGRectMake(self.view.frame.size.width - 52, 0, 35, 35);
    
    
    
    UIView *viewOfGrayLine = [[UIView alloc] initWithFrame:CGRectMake(0, self.viewOfHistory.frame.size.height - 1, self.viewOfHistory.frame.size.width, 1)];
    [self.viewOfHistory addSubview:viewOfGrayLine];
    [viewOfGrayLine release];
    
    viewOfGrayLine.layer.borderColor = [UIColor colorWithRed:0.8357 green:0.8357 blue:0.8357 alpha:1.0].CGColor;
    viewOfGrayLine.layer.borderWidth = 1;
    
#pragma mark - 创建历史collectionView
    SearchOfFlowLayout *flowLayout = [[SearchOfFlowLayout alloc] init];
    
    flowLayout.sectionInset = UIEdgeInsetsMake(15, 15, 15, 15);
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.minimumInteritemSpacing = 15;
    flowLayout.minimumLineSpacing = 15;
    flowLayout.insertItemSpacing = 15;
    
    flowLayout.itemSize = CGSizeMake(50, 35);
    flowLayout.delegate = self;
    
    self.collectionOfHistory = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 40, self.view.frame.size.width, 60 - 40) collectionViewLayout:flowLayout];
    [self.viewOfHistory addSubview:self.collectionOfHistory];
    [_collectionOfHistory release];
    self.collectionOfHistory.dataSource = self;
    self.collectionOfHistory.delegate = self;
    
    self.collectionOfHistory.backgroundColor = [UIColor colorWithRed:0.9686 green:0.9686 blue:0.9686 alpha:1.0];
    
    
    [self.collectionOfHistory registerClass:[CellOfSearchForCollection class] forCellWithReuseIdentifier:@"poolOfCellForHistory"];
    

    
#pragma mark - 创建热门搜索图层
    self.viewOfHotSearch = [[UIView alloc] initWithFrame:CGRectMake(0, self.viewOfHistory.frame.origin.y + self.viewOfHistory.frame.size.height, self.view.frame.size.width, 350)];
    [self.view addSubview:self.viewOfHotSearch];
    [_viewOfHotSearch release];
    
    self.viewOfHotSearch.backgroundColor = [UIColor colorWithRed:0.9686 green:0.9686 blue:0.9686 alpha:1.0];
    
    UIImageView *imageViewOfHot = [[UIImageView alloc] initWithFrame:CGRectMake(0, 5, self.viewOfHotSearch.frame.size.width, 35)];
    [self.viewOfHotSearch addSubview:imageViewOfHot];
    [imageViewOfHot release];
    
    imageViewOfHot.image = [UIImage imageNamed:@"HotSearch"];
    
#pragma mark - 创建热门collectionView
    
    SearchOfFlowLayout *flowLayout2 = [[SearchOfFlowLayout alloc] init];
    
    flowLayout2.sectionInset = UIEdgeInsetsMake(15, 15, 15, 15);
    flowLayout2.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout2.minimumInteritemSpacing = 15;
    flowLayout2.minimumLineSpacing = 15;
    flowLayout2.insertItemSpacing = 15;
    
    flowLayout2.itemSize = CGSizeMake(50, 35);
    flowLayout2.delegate = self;
    
    self.collectionOfHot = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 35, self.viewOfHotSearch.frame.size.width, self.viewOfHotSearch.frame.size.height - 35) collectionViewLayout:flowLayout2];
    [self.viewOfHotSearch addSubview:self.collectionOfHot];
    [_collectionOfHot release];
    self.collectionOfHot.dataSource = self;
    self.collectionOfHot.delegate = self;
    
    self.collectionOfHot.backgroundColor = [UIColor colorWithRed:0.9686 green:0.9686 blue:0.9686 alpha:1.0];
    
    
    [self.collectionOfHot registerClass:[CellOfSearchForCollection class] forCellWithReuseIdentifier:@"poolOfCellForHot"];
    
    
    

}

#pragma mark - 实现collectionViewFlowLayout代理方法
- (CGFloat)widthForItemIndexPath:(NSIndexPath *)indexPath AndCollectioinView:(UICollectionView *)collectionView{
    NSString *content = nil;
    if (collectionView == self.collectionOfHot) {
        content = self.hotTagArr[indexPath.item];
        
    }else {
        content = self.historyArr[indexPath.item];
    }
    CGRect itemFrame = [content boundingRectWithSize:CGSizeMake(0, 20) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:17]} context:nil];
    
    CGFloat width = itemFrame.size.width + 20;
    
    return width;
}

- (void)setCollectionViewFrameWithCollectionView:(UICollectionView *)collection AndSize:(CGSize)size{
    if (collection == self.collectionOfHot) {
        self.viewOfHotSearch.frame = CGRectMake(0, self.viewOfHistory.frame.origin.y + self.viewOfHistory.frame.size.height, size.width, size.height + 40);

    }else {
        if (self.historyArr.count > 0) {
            self.viewOfHistory.frame = CGRectMake(0, self.viewOfHistory.frame.origin.y, size.width, size.height + 40);
            self.viewOfHotSearch.frame = CGRectMake(0, self.viewOfHistory.frame.origin.y + self.viewOfHistory.frame.size.height, self.viewOfHotSearch.frame.size.width, self.viewOfHotSearch.frame.size.height);
        }else {
            self.viewOfHistory.frame = CGRectMake(0, 60, self.view.frame.size.width, 60);
            [UIView animateWithDuration:0.3 animations:^{
                self.viewOfHotSearch.frame = CGRectMake(0, self.viewOfHistory.frame.origin.y + self.viewOfHistory.frame.size.height, self.viewOfHotSearch.frame.size.width, self.viewOfHotSearch.frame.size.height);

            }];
        }

    }

}


#pragma mark - 点击清除按钮
- (void)handleClearAction {
    //删除表
    [[DataBaseHandle shareDataBaseHandle] updateSQL:@"DROP TABLE history"];
    //创建SQL语句.
    NSString *createTableSQL = @"CREATE TABLE IF NOT EXISTS history(number INTEGER PRIMARY KEY AUTOINCREMENT, content text)";
    [[DataBaseHandle shareDataBaseHandle] updateSQL:createTableSQL];
    self.historyArr = nil;
    
    [self.collectionOfHistory reloadData];

}

#pragma mark - 创建头部搜索以及取消图层
- (void)createHeaderView {
    
    UIView *viewOfHeader = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 60)];
    [self.view addSubview:viewOfHeader];
    [viewOfHeader release];
    
    viewOfHeader.backgroundColor = [UIColor whiteColor];
    
    UIView *viewOfGray = [[UIView alloc] initWithFrame:CGRectMake(10, 25, self.view.frame.size.width - 80, 30)];
    [viewOfHeader addSubview:viewOfGray];
    [viewOfGray release];
    viewOfGray.backgroundColor = [UIColor colorWithRed:0.9686 green:0.9686 blue:0.9686 alpha:1.0];
    viewOfGray.layer.cornerRadius = 7;
    viewOfGray.layer.masksToBounds = YES;
    
#pragma mark - 设置搜索textField
    self.textFieldOfSearch = [[KeyInputTextFiled alloc] initWithFrame:CGRectMake(10, 2, viewOfGray.frame.size.width - 15, 28)];
    [viewOfGray addSubview:self.textFieldOfSearch];
    [_textFieldOfSearch release];
    self.textFieldOfSearch.backgroundColor = [UIColor colorWithRed:0.9686 green:0.9686 blue:0.9686 alpha:1.0];
    self.textFieldOfSearch.placeholder = @"查找用户名，帖子，标签";
    self.textFieldOfSearch.delegate = self;
    self.textFieldOfSearch.returnKeyType = UIReturnKeySearch;
    
    self.textFieldOfSearch.keyInputDelegate = self;

#pragma mark - textFiled监听事件
    
    
    
    
    
    
    self.labelOfNumb = [[UILabel alloc] initWithFrame:CGRectMake(viewOfGray.frame.size.width - 45, 0, 45, 30)];
    [viewOfGray addSubview:self.labelOfNumb];
    [_labelOfNumb release];
    self.labelOfNumb.textColor = [UIColor grayColor];
    self.labelOfNumb.text = @"0/12";
    self.labelOfNumb.font = [UIFont systemFontOfSize:15];
    
    
    
    UIButton *buttonOfCancel = [UIButton buttonWithType:UIButtonTypeSystem];
    [viewOfHeader addSubview:buttonOfCancel];
    
    buttonOfCancel.frame = CGRectMake(self.view.frame.size.width - 55, 25, 40, 30);
    [buttonOfCancel setTitle:@"取消" forState:UIControlStateNormal];
    
    [buttonOfCancel addTarget:self action:@selector(handleAction:) forControlEvents:UIControlEventTouchUpInside];
    buttonOfCancel.titleLabel.font = [UIFont systemFontOfSize:20];
    

}


#pragma mark - textFiled代理实现

- (void)textFieldDidChange:(UITextField *)textField {
    
    if (textField.text.length == 0){
        return;
    }else {
        
    }
    if (textField.text.length > 12) {
        textField.text = [textField.text substringToIndex:12];
    }
    self.labelOfNumb.text = [NSString stringWithFormat:@"%ld/12", textField.text.length];
    
    
    
    if (self.timerOfSearch) {
        [self.timerOfSearch invalidate];
        self.timerOfSearch = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(handleTimer) userInfo:nil repeats:NO];
    }else {
        self.timerOfSearch = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(handleTimer) userInfo:nil repeats:NO];
    }
}

#pragma mark - 实现删除功能
- (void)deleteBackward {
    
    
    if (self.timerOfSearch) {
        [self.timerOfSearch invalidate];
        self.timerOfSearch = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(handleTimer) userInfo:nil repeats:NO];
    }else {
        self.timerOfSearch = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(handleTimer) userInfo:nil repeats:NO];
    }
    self.labelOfNumb.text = [NSString stringWithFormat:@"%ld/12", self.self.textFieldOfSearch.text.length];
    if (self.textFieldOfSearch.text.length == 0) {
        [self.timerOfSearch invalidate];
        self.viewOfHistory.hidden = NO;
        self.viewOfHotSearch.hidden = NO;
        self.tableView.hidden = YES;
    }
    
    
}



#pragma mark - textFiled的计时器并且跳转页面
- (void)handleTimer {
    
    [self handleData];
}

#pragma mark ** 取消按钮实现功能
- (void)handleAction:(UIButton *)button {
    [self.timerOfSearch invalidate];
    self.viewOfHistory.hidden = NO;
    self.viewOfHotSearch.hidden = NO;
    self.tableView.hidden = YES;
    self.labelOfNumb.text = @"0/12";
    if ([self.textFieldOfSearch.text isEqualToString:@""]) {
        
        [self.navigationController popViewControllerAnimated:YES];
        /** 把navigationBar的位置移动回来 */
        self.navigationController.navigationBar.frame = CGRectMake(0, 20, self.view.frame.size.width, 44);
    }else {
        
        self.textFieldOfSearch.text = @"";
    }
    
    
}

#pragma mark - 点击textField的return实现搜索
- (BOOL)textFieldShouldReturn:(UITextField *)textField {

    [self.timerOfSearch invalidate];
    [self handleData];

    return YES;
}


#pragma mark - 点击释放第一响应
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {

    [self.view endEditing:YES];

}
#pragma mark - 隐藏navigation
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    /** 把navigationBar的位置移动到上方隐藏起来 */
    self.navigationController.navigationBar.frame = CGRectMake(0, -44, self.view.frame.size.width, 44);
    
    NSArray *result = [[DataBaseHandle shareDataBaseHandle] selectAllWithList:@"history" AndListNumber:2];
    self.historyArr = [NSMutableArray array];
    for (NSArray *arr in result) {
        [self.historyArr addObject:arr[1]];
    }
    [self.collectionOfHistory reloadData];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
